const {
  Passport
} = require('@casstime/passport');
const proxy = require('http-proxy-middleware');

const passport = new Passport({
  clientId: 'cassdev',
  secretKey: '123456',
  origin: 'https://test-api.casstime.com'
});

// 当前登录的用户名和密码
const userLoginId = 'mandy';
const password = 'Cass1713';


const ACCESS_TOKEN_KEY = 'ACCESS_TOKEN';
module.exports = function (app) {
  app.use(async (req, res, next) => {
    if (!app.get(ACCESS_TOKEN_KEY)) {
      try {
        const {
          access_token
        } = await passport.getTokensByPassword(userLoginId, password);
        app.set(ACCESS_TOKEN_KEY, access_token);
      } catch (err) {
        console.error('测试环境鉴权失败', err);
        next(err);
        return;
      }
    }
    next();
  });

  // https://github.com/chimurai/http-proxy-middleware
  app.use(proxy(['/terminal-api'], {
    target: 'https://ec-test.casstime.com/',
    changeOrigin: true,
    onProxyReq(proxyReq, req, res) {
      // 为代理的请求增加authorization头
      proxyReq.setHeader('Authorization', `bearer ${app.get(ACCESS_TOKEN_KEY)}`);
    }
  }));
}
